import {
  orderList,
  orderPayment,
  orderQuery,
  orderCancel
} from '../../apis/user';
import {
  splicing,
  formatTime,
  handleDate
} from '../../utils/util';
const app = getApp();

Page({
  data: {
    navList: [{
      nav: 0,
      name: '全部'
    }, {
      nav: 1,
      name: '待审核'
    }, {
      nav: 3,
      name: '待支付'
    }, {
      nav: 4,
      name: '待参加'
    }, {
      nav: 5,
      name: '已完成'
    }],
    navIndex: 0,
    orderList: [],
    pageNum: 1,
    isHaveMore: true,
    isRequest: false
  },

  onLoad(options) {
    this.setData({
      ...options
    });
  },

  onShow() {
    this.setData({
      pageNum: 1,
      isHaveMore: true
    });
    this.getOrderList(this.data.navList[this.data.navIndex].nav, 1);
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.getOrderList(this.data.navList[this.data.navIndex].nav, 1);
  },

  // 页面触底
  onReachBottom() {
    if (this.data.isHaveMore && !this.data.isRequest) {
      this.getOrderList(this.data.navList[this.data.navIndex].nav, this.data.pageNum + 1, 'load');
    };
  },

  // 获取列表
  getOrderList(nav, pageNum, type) {
    if (this.data.isRequest) return
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    this.setData({
      isRequest: true
    });
    orderList(nav, pageNum, 10).then(res => {
      wx.hideLoading();
      wx.stopPullDownRefresh();
      this.setData({
        isRequest: false
      });
      if (res.data.code === 200) {
        this.setData({
          pageNum: pageNum
        });
        let {
          rows,
          total
        } = res.data;
        rows.forEach(v => {
          v.createTime = formatTime(v.createTime);
          v.orderDetail.imageList = v.orderDetail.imageList.map(val => val = splicing(val));
          v.orderDetail.startTime = handleDate(v.orderDetail.startTime);
          v.orderDetail.closeTime = handleDate(v.orderDetail.closeTime);
        });
        if (type === 'load') {
          rows.forEach(v => {
            this.data.orderList.push(v);
          });
          this.setData({
            orderList: this.data.orderList
          });
        } else {
          this.setData({
            orderList: rows
          });
        };

        if (this.data.orderList.length === total) {
          this.setData({
            isHaveMore: false
          });
        };
      };
    });
  },

  // 改变导航
  changeNav(e) {
    let {
      index
    } = e.currentTarget.dataset;
    this.setData({
      navIndex: index,
      pageNum: 1,
      isHaveMore: true
    });
    this.getOrderList(this.data.navList[index].nav, 1);
  },

  // 详情
  orderDetails(e) {
    let {
      num
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/orderDetails/index?orderNo=${num}`
    });
  },

  action(e) {
    let {
      index,
      status,
      pstatus
    } = e.currentTarget.dataset;
    if (status == 0 || status == 5) { // 查看详情
      wx.navigateTo({
        url: `/pages/orderDetails/index?orderNo=${this.data.orderList[index].orderNo}`
      });
    } else if (status == 1) { // 取消报名
      wx.showModal({
        title: '确定取消该活动报名吗？',
        success: res => {
          if (res.confirm) {
            this.cancelSignUp(this.data.orderList[index].orderNo, index);
          };
        }
      });
    } else if (status == 2) { // 重新报名
      wx.navigateTo({
        url: `/pages/editUserInfo/index?type=activity&from=order&activityId=${this.data.orderList[index].activityId}&orderNo=${this.data.orderList[index].orderNo}`
      });
    } else if (status == 3 && pstatus == 0) { // 付钱
      this.payment(this.data.orderList[index].orderNo, index);
    } else if ((status == 3 && pstatus == 1) || status == 4) { // 二维码
      wx.navigateTo({
        url: `/pages/orderDetails/index?orderNo=${this.data.orderList[index].orderNo}`
      });
    };
  },

  // 支付
  payment(orderNo, index) {
    // wx.requestSubscribeMessage({
    //   tmplIds: ['_quuyfAlYNQwnbSdnyvgXveDHPNZ99V3h072l0jRhHs', 'pE5LxEcdYHS6B-TiE45j-GjiX-aV9e-KrHagJ1h4bbQ'],
    //   complete: res => {}
    // });
    wx.showLoading({
      title: '请稍候...',
    });
    orderPayment(orderNo).then(res => {
      wx.hideLoading();
      if (res.data.code === 200) {
        let {
          needPay,
          result
        } = res.data.data;
        if (needPay) {
          wx.requestPayment({
            nonceStr: result.nonceStr,
            package: result.packageValue,
            paySign: result.paySign,
            timeStamp: result.timeStamp,
            signType: result.signType,
            success: res => {
              this.paymentQuery(orderNo, index);
            },
            fail: res => {
              this.paymentQuery(orderNo, index);
            }
          });
        } else {
          this.paymentQuery(orderNo, index);
        };
      };
    });
  },

  // 支付查询
  paymentQuery(orderNo, index) {
    orderQuery(orderNo).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        if (data.isPay) {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            mask: true,
            duration: 1500
          });
        };
        this.getOrderList(this.data.navList[this.data.navIndex].nav, 1);
      };
    });
  },

  // 取消报名
  cancelSignUp(orderNo, index) {
    orderCancel(orderNo).then(res => {
      if (res.data.code === 200) {
        wx.showToast({
          title: '取消成功',
          duration: 1000,
          icon: 'success',
          mask: true
        });
        this.setData({
          [`orderList[${index}].orderStatus`]: 0
        });
      };
    });
  }
})